package com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.resp_ok;

import com.clp.protocol.modbus_tcp.definition.CoilStatus;
import com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.RespOkMbData;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Objects;

/**
 * 读线圈正确响应
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ReadCoilStatusRespOkMbData implements RespOkMbData {
    /**
     * 字节计数
     */
    private int byteCount;

    /**
     * 线圈状态列表
     */
    private List<CoilStatus> coilStatuses;

    @Override
    public ReadCoilStatusRespOkMbData initBy(ByteBuf buf) {
        this.byteCount = buf.readByte() & 0xFF;
        byte[] coilStatusesBytes = new byte[byteCount]; buf.readBytes(coilStatusesBytes);
        this.coilStatuses = CoilStatus.gainList(coilStatusesBytes);
        return this;
    }

    @Override
    public boolean isValid() {
        if (byteCount < 0 || byteCount > 0xFF) return false;
        return coilStatuses != null && byteCount * 8 >= coilStatuses.size();
    }

    @Override
    public void writeTo(ByteBuf buf) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("字节计数：" + byteCount + ", 线圈状态列表：");
        for (int i = 0; i < coilStatuses.size(); i++) {
            if (i % 8 == 0) {
                sb.append(" ");
            }
            sb.append(coilStatuses.get(i).getVal());
        }
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ReadCoilStatusRespOkMbData that = (ReadCoilStatusRespOkMbData) o;
        return byteCount == that.byteCount && Objects.equals(coilStatuses, that.coilStatuses);
    }

    @Override
    public int hashCode() {
        return Objects.hash(byteCount, coilStatuses);
    }
}
